package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.entity.SysRight;
import com.ktjy.entity.SysUser;
import com.ktjy.service.ISysRightService;
import com.ktjy.service.ISysUserService;
import com.ktjy.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
public class LoginController {


    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ISysUserService service;

    @Autowired
    ISysRightService sysRightService;


    @RequestMapping("/customer/login")
    public Object login(String username, String password) {
        System.out.println(username + "," + password);
//        System.out.println(sysUser1.get("username") + "," +sysUser1.get("password") );
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUsrName, username);
        queryWrapper.lambda().eq(SysUser::getUsrPassword, password);

        SysUser sysUser = service.getOne(queryWrapper);

        if (sysUser != null) {
            String token = UUID.randomUUID().toString();
            List<SysRight> list = sysRightService.getListByRoleId(sysUser.getUsrRoleId());
            List<String> rights = list.stream().map(temp -> {
                return temp.getRightCode();
            }).toList();
            sysUser.setRightList(rights);

//            SecurityContextHolder.getContext().setAuthentication(
//                    new UsernamePasswordAuthenticationToken(sysUser.getUsrName(),
//                            new BCryptPasswordEncoder().encode(sysUser.getUsrPassword()), Collections.EMPTY_LIST));
            redisUtils.set(token,   sysUser);
            return token;
        } else {
            return "";
        }


    }


}
